package com.uzai.console.service.faq.privatework.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.faq.privatework.*;
import com.uzai.console.entity.FaqKeyword;
import com.uzai.console.entity.FaqReply;
import com.uzai.console.entity.FaqReplyGroup;
import com.uzai.console.jsonvo.faqkeyword.RiskRule;
import com.uzai.console.mapper.FaqKeywordMapper;
import com.uzai.console.mapper.FaqReplyGroupMapper;
import com.uzai.console.mapper.FaqReplyMapper;
import com.uzai.console.service.faq.privatework.FaqReplyService;
import com.uzai.console.vo.faq.privatework.FaqKeywordInfoVo;
import com.uzai.console.vo.faq.privatework.FaqReplyInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author liuqi
 * @date 2021年08月23日 20:25
 */
@Service
public class FaqReplyServiceImpl implements FaqReplyService {

    @Autowired
    private FaqReplyMapper faqReplyMapper;
    @Autowired
    private FaqKeywordMapper faqKeywordMapper;
    @Autowired
    private FaqReplyGroupMapper faqReplyGroupMapper;

    /**
     * 智能回复问答回复语列表
     *
     * @param faqReplyQuery
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public Page<FaqReplyInfoVo> findFaqReplyList(FaqReplyQuery faqReplyQuery) {
        //新建返回到页面的LIST对象
        List<FaqReplyInfoVo> faqReplyPageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<FaqReply> page = new Page<>();
        faqReplyQuery.convert(page);
        ArrayList<FaqReply> faqReplyList = faqReplyMapper.findByList(page, faqReplyQuery);
        if (faqReplyList != null && faqReplyList.size() > 0) {
            for (FaqReply faqReply : faqReplyList) {
                FaqReplyInfoVo faqReplyPageVo = new FaqReplyInfoVo();
                BeanUtils.copyProperties(faqReply, faqReplyPageVo);
                //分组信息
                if (faqReply.getGroupId() != null) {
                    FaqReplyGroup faqReplyGroup = faqReplyGroupMapper.selectById(faqReply.getGroupId(), faqReply.getMerId());
                    if (faqReplyGroup != null) {
                        faqReplyPageVo.setGroupName(faqReplyGroup.getName());
                    }
                }


                JSONObject contentObject = null;
                try {
                    contentObject = JSONObject.parseObject(faqReply.getContent());
                }catch (Exception e){

                }

                if (contentObject == null) {
                    contentObject = new JSONObject();
                }

                if (faqReply.getType() == 0) {//常规回复
                    faqReplyPageVo.setContent(contentObject.getString("content"));
                } else if (faqReply.getType() == 1) {//卡片回复
                    faqReplyPageVo.setCardTitle(contentObject.getString("cardTitle"));
                    faqReplyPageVo.setCardUrl(contentObject.getString("cardUrl"));
                    faqReplyPageVo.setCardImg(contentObject.getString("cardImg"));
                    faqReplyPageVo.setCardDesc(contentObject.getString("cardDesc"));
                } else if (faqReply.getType() == 2) {//小程序回复
                    faqReplyPageVo.setMiniProName(contentObject.getString("miniProName"));
                    faqReplyPageVo.setMiniProTitle(contentObject.getString("miniProTitle"));
                    faqReplyPageVo.setMiniProUrl(contentObject.getString("miniProUrl"));
                    faqReplyPageVo.setMiniProDesc(contentObject.getString("miniProDesc"));
                    faqReplyPageVo.setMiniImgPwdStr(contentObject.getString("miniImgPwdStr"));
                    faqReplyPageVo.setMiniImgStr(contentObject.getString("miniImgStr"));
                    faqReplyPageVo.setMiniImgPwdStrWxwork(contentObject.getString("miniImgPwdStrWxwork"));
                    faqReplyPageVo.setMiniImgStrWxwork(contentObject.getString("miniImgStrWxwork"));
                    faqReplyPageVo.setMiniImgUrl(contentObject.getString("miniImgUrl"));
                    faqReplyPageVo.setMiniProAppId(contentObject.getString("miniProAppId"));
                    faqReplyPageVo.setMiniProGhId(contentObject.getString("miniProGhId"));
                } else if (faqReply.getType() == 3) {//微信好友名片
                    faqReplyPageVo.setWxid(contentObject.getString("wxid"));
                    faqReplyPageVo.setWorkWxid(contentObject.getString("workWxid"));
                } else if (faqReply.getType() == 4) { //拉群规则
                    if (contentObject != null) {
                        faqReplyPageVo.setContent(contentObject.getString("content"));
                        faqReplyPageVo.setPullGroupRuleJsonStr(contentObject.getString("content"));
                    }
                } else if (faqReply.getType() == 5) { //超级问答
                    if (contentObject != null) {
                        faqReplyPageVo.setContent(contentObject.getString("content"));
                        faqReplyPageVo.setSuperReplyJsonStr(contentObject.getString("content"));
                    }
                } else if(faqReply.getType().intValue() == 6){ //关键词拉群（风险监控）
                    if (contentObject != null) {
                        faqReplyPageVo.setContent(contentObject.getString("content"));
                        faqReplyPageVo.setPullGroupByKeywordJsonStr(contentObject.getString("content"));
                    }
                }

                //关键字列表
                FaqKeywordQuery faqKeywordQuery = new FaqKeywordQuery();
                faqKeywordQuery.setMerId(faqReply.getMerId());
                faqKeywordQuery.setReplyId(faqReply.getId());
                List<FaqKeyword> faqKeywordList = faqKeywordMapper.findByList(faqKeywordQuery);
                if (faqKeywordList != null && faqKeywordList.size() > 0) {
                    List<FaqKeywordInfoVo> faqKeywordInfoVoList = new ArrayList<>();
                    List<String> keywordList = new ArrayList<>();
                    for (FaqKeyword faqKeyword : faqKeywordList) {
                        FaqKeywordInfoVo faqKeywordInfoVo = new FaqKeywordInfoVo();
                        BeanUtils.copyProperties(faqKeyword, faqKeywordInfoVo);

                        //会员标签
                        String userTags = faqKeyword.getUserTags();
                        if (StringUtils.isNotBlank(userTags)) {
                            try {
                                List<Long> userTagsList = JSONObject.parseArray(userTags, Long.class);
                                faqKeywordInfoVo.setUserTagsList(userTagsList);
                            } catch (Exception e) {

                            }
                        }

                        //忽略自定义标签
                        String ignoreTags = faqKeyword.getIgnoreTags();
                        if (StringUtils.isNotBlank(ignoreTags)) {
                            try {
                                List<String> ignoreTagsList = JSONObject.parseArray(ignoreTags, String.class);
                                faqKeywordInfoVo.setIgnoreTagsList(ignoreTagsList);
                            } catch (Exception e) {

                            }
                        }

                        //忽略会员备注标签
                        String ignoreRemarks = faqKeyword.getIgnoreRemarks();
                        if (StringUtils.isNotBlank(ignoreRemarks)) {
                            try {
                                List<String> ignoreRemarksList = JSONObject.parseArray(ignoreRemarks, String.class);
                                faqKeywordInfoVo.setIgnoreRemarksList(ignoreRemarksList);
                            } catch (Exception e) {

                            }
                        }

                        //风控规则
                        String riskRuleStr = faqKeyword.getRiskRule();
                        if (StringUtils.isNotBlank(riskRuleStr)) {
                            try {
                                RiskRule riskRule = JSONObject.parseObject(riskRuleStr, RiskRule.class);
                                faqKeywordInfoVo.setRiskRule(riskRule);
                            } catch (Exception e) {

                            }
                        }

                        faqKeywordInfoVoList.add(faqKeywordInfoVo);
                        keywordList.add(faqKeyword.getKeyword());
                    }
                    faqReplyPageVo.setFaqKeywordInfoVoList(faqKeywordInfoVoList);
                    faqReplyPageVo.setKeywordList(keywordList);
                }
                faqReplyPageVoList.add(faqReplyPageVo);
            }
        }
        //返回到页面分页对象
        Page<FaqReplyInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(faqReplyPageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 添加超级问答回复语
     *
     * @param faqReplyInfoDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Transactional
    public void addFaqReply(FaqReplyInfoDto faqReplyInfoDto) {

        if (faqReplyInfoDto.getType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入回复语类型");
        }

        if (faqReplyInfoDto.getFaqKeywordInfoDtoList() == null || faqReplyInfoDto.getFaqKeywordInfoDtoList().size() < 1) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请增加关键词");
        }

        FaqReply faqReply = new FaqReply();
        BeanUtils.copyProperties(faqReplyInfoDto, faqReply);

        //封装content信息
        HashMap hm = new HashMap();
        hm.put("type", faqReplyInfoDto.getType());
        if (faqReplyInfoDto.getType().intValue() == 0) { //常规回复

//            if(Tools.getStr(faqReplyInfoDto.getContent()).contains("超级指令")){
////                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "智能回复的回复语中暂不支持“超级指令”请修改!");
////            }

            hm.put("content", faqReplyInfoDto.getContent());
            faqReply.setContent(Tools.getStrEmpty(JSONObject.toJSONString(hm)));
        } else if (faqReply.getType().intValue() == 1) {  //卡片回复
            hm.put("cardTitle", faqReplyInfoDto.getCardTitle());
            hm.put("cardDesc", faqReplyInfoDto.getCardDesc());
            hm.put("cardUrl", faqReplyInfoDto.getCardUrl());
            hm.put("cardImg", faqReplyInfoDto.getCardImg());
            //--2023-11-27修改
            hm.put("appName", faqReplyInfoDto.getAppName());
            hm.put("appId", faqReplyInfoDto.getAppId());
            hm.put("appVersion", faqReplyInfoDto.getAppVersion());
            faqReply.setContent(Tools.getStrEmpty(JSONObject.toJSONString(hm)));
        } else if (faqReply.getType().intValue() == 2) { //小程序回复
            hm.put("miniProTitle", faqReplyInfoDto.getMiniProTitle());
            hm.put("miniProDesc", faqReplyInfoDto.getMiniProDesc());
            hm.put("miniProName", faqReplyInfoDto.getMiniProName());
            hm.put("miniProUrl", faqReplyInfoDto.getMiniProUrl());
            hm.put("miniImgPwdStr", faqReplyInfoDto.getMiniImgPwdStr());
            hm.put("miniImgStr", faqReplyInfoDto.getMiniImgStr());
            hm.put("miniImgPwdStrWxwork", faqReplyInfoDto.getMiniImgPwdStrWxwork());
            hm.put("miniImgStrWxwork", faqReplyInfoDto.getMiniImgStrWxwork());
            hm.put("miniImgUrl", faqReplyInfoDto.getMiniImgUrl());
            hm.put("miniProAppId", faqReplyInfoDto.getMiniProAppId());
            hm.put("miniProGhId", faqReplyInfoDto.getMiniProGhId());
            faqReply.setContent(Tools.getStrEmpty(JSONObject.toJSONString(hm)));
        } else if (faqReply.getType().intValue() == 3) { //添加微信好友名片回复
            hm.put("wxid", faqReplyInfoDto.getWxid());
            hm.put("workWxid", faqReplyInfoDto.getWorkWxid());
            faqReply.setContent(Tools.getStrEmpty(JSONObject.toJSONString(hm)));
        } else if (faqReply.getType().intValue() == 4) {
            hm.put("content", faqReplyInfoDto.getPullGroupRuleJsonStr());
            faqReply.setContent(Tools.getStrEmpty(JSONObject.toJSONString(hm)));
        } else if (faqReply.getType().intValue() == 5) { //超级问答
            hm.put("content", faqReplyInfoDto.getSuperReplyJsonStr());
            faqReply.setContent(Tools.getStrEmpty(JSONObject.toJSONString(hm)));
        } else if(faqReply.getType().intValue() == 6){ //关键词拉群（风险监控）
            hm.put("content", faqReplyInfoDto.getPullGroupByKeywordJsonStr());
            faqReply.setContent(Tools.getStrEmpty(JSONObject.toJSONString(hm)));
        }

        Integer now = DateUtil.getNowTime();
        Long replyId = IdWorker.getId();
        faqReply.setId(replyId);
        faqReply.setCreateTime(now);
        faqReply.setUpdateTime(now);
        faqReply.setStatus(1); //默认启用
        faqReplyMapper.insert(faqReply);

        //关键词list
        for (FaqKeywordInfoDto faqKeywordInfoDto : faqReplyInfoDto.getFaqKeywordInfoDtoList()) {

            faqKeywordInfoDto.setMerId(faqReplyInfoDto.getMerId());

            if (faqKeywordInfoDto.getType() == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "触发类型不能为空");
            }
            if (StringUtils.isBlank(faqKeywordInfoDto.getKeyword())) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CIKUKEY_NULL);
            }
            if (StringUtils.isBlank(faqKeywordInfoDto.getDeviceType())) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备类型不能为空");
            }

            //最大时间为30天内
            if (Tools.getInteger(faqKeywordInfoDto.getMaxTime()).intValue() > 30 * 24 * 60) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "同一用户最大时间不能超过30天(30*24*60)");
            }

            //未选择机器人，判断该关键字是否存在，
            if (Tools.getLong(faqKeywordInfoDto.getDeviceUniqueId()).longValue() == 0) {
                FaqKeywordQuery faqKeywordQuery = new FaqKeywordQuery();
                faqKeywordQuery.setMerId(faqKeywordInfoDto.getMerId());
                faqKeywordQuery.setKeyword(faqKeywordInfoDto.getKeyword());
                faqKeywordQuery.setDeviceType(faqKeywordInfoDto.getDeviceType());
                List<FaqKeyword> faqKeywordList = faqKeywordMapper.findByList(faqKeywordQuery);
                if (faqKeywordList != null && faqKeywordList.size() > 0) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, String.format(ResponseMsg.CIKUKEY_EXIST, faqKeywordInfoDto.getKeyword()));
                }
            } else {//选择了机器人，
                //1-判断该机器人下是否关键字重复
                FaqKeyword nowKey = faqKeywordMapper.getByKeywordAndDeviceUniqueId(faqKeywordInfoDto.getKeyword(), faqReplyInfoDto.getMerId(), faqKeywordInfoDto.getDeviceUniqueId(), faqKeywordInfoDto.getDeviceType());
                if (nowKey != null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, String.format(ResponseMsg.CIKUKEY_EXIST, faqKeywordInfoDto.getKeyword()));
                }
                //2-判断是否有未选择机器人配置了该关键字
                FaqKeyword nowKey_0 = faqKeywordMapper.getByKeywordAndDeviceUniqueId(faqKeywordInfoDto.getKeyword(), faqReplyInfoDto.getMerId(), 0L, faqKeywordInfoDto.getDeviceType());
                if (nowKey_0 != null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, String.format(ResponseMsg.CIKUKEY_EXIST, faqKeywordInfoDto.getKeyword()));
                }
            }

            FaqKeyword ck_new = new FaqKeyword();
            BeanUtils.copyProperties(faqKeywordInfoDto, ck_new);
            ck_new.setId(IdWorker.getId());
            ck_new.setMerId(faqReplyInfoDto.getMerId());
            ck_new.setReplyId(replyId);
            ck_new.setPlatform(0);//0客户端(个微/企微);1公众号;2小程序;3app;(预留字段)
            ck_new.setCreateTime(now);
            ck_new.setUpdateTime(now);
            //会员标签
            ck_new.setUserTags(Tools.getStrEmpty(JSONObject.toJSONString(faqKeywordInfoDto.getUserTagsList())));
            //忽略自定义标签
            ck_new.setIgnoreTags(Tools.getStrEmpty(JSONObject.toJSONString(faqKeywordInfoDto.getIgnoreTagsList())));
            //忽略会员备注列表
            ck_new.setIgnoreRemarks(Tools.getStrEmpty(JSONObject.toJSONString(faqKeywordInfoDto.getIgnoreRemarksList())));
            //风控规则
            ck_new.setRiskRule(Tools.getStrEmpty(JSONObject.toJSONString(faqKeywordInfoDto.getRiskRule())));
            faqKeywordMapper.insertSelective(ck_new);
        }

    }

    /**
     * 修改超级问答回复语
     *
     * @param faqReplyInfoDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Transactional
    public void updateFaqReply(FaqReplyInfoDto faqReplyInfoDto) {

        if (faqReplyInfoDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        if (faqReplyInfoDto.getType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入回复语类型");
        }

        if (faqReplyInfoDto.getFaqKeywordInfoDtoList() == null || faqReplyInfoDto.getFaqKeywordInfoDtoList().size() < 1) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请增加关键词");
        }

        FaqReply faqReply = faqReplyMapper.selectById(faqReplyInfoDto.getId(), faqReplyInfoDto.getMerId());

        if (faqReply == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该回复语不存在");
        }

        //封装content信息
        HashMap hm = new HashMap();
        hm.put("type", faqReplyInfoDto.getType());
        if (faqReplyInfoDto.getType() == 0) { //常规回复
//            if(Tools.getStr(faqReplyInfoDto.getContent()).contains("超级指令")){
//                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "智能回复的回复语中暂不支持“超级指令”请修改!");
//            }

            hm.put("content", faqReplyInfoDto.getContent());
            faqReply.setContent(Tools.getStrEmpty(JSONObject.toJSONString(hm)));
        } else if (faqReply.getType() == 1) {  //卡片回复
            hm.put("cardTitle", faqReplyInfoDto.getCardTitle());
            hm.put("cardDesc", faqReplyInfoDto.getCardDesc());
            hm.put("cardUrl", faqReplyInfoDto.getCardUrl());
            hm.put("cardImg", faqReplyInfoDto.getCardImg());
            //--2023-11-27修改
            hm.put("appName", faqReplyInfoDto.getAppName());
            hm.put("appId", faqReplyInfoDto.getAppId());
            hm.put("appVersion", faqReplyInfoDto.getAppVersion());
            faqReply.setContent(Tools.getStrEmpty(JSONObject.toJSONString(hm)));
        } else if (faqReply.getType() == 2) { //小程序回复
            hm.put("miniProTitle", faqReplyInfoDto.getMiniProTitle());
            hm.put("miniProDesc", faqReplyInfoDto.getMiniProDesc());
            hm.put("miniProName", faqReplyInfoDto.getMiniProName());
            hm.put("miniProUrl", faqReplyInfoDto.getMiniProUrl());
            hm.put("miniImgPwdStr", faqReplyInfoDto.getMiniImgPwdStr());
            hm.put("miniImgStr", faqReplyInfoDto.getMiniImgStr());
            hm.put("miniImgPwdStrWxwork", faqReplyInfoDto.getMiniImgPwdStrWxwork());
            hm.put("miniImgStrWxwork", faqReplyInfoDto.getMiniImgStrWxwork());
            hm.put("miniImgUrl", faqReplyInfoDto.getMiniImgUrl());
            hm.put("miniProAppId", faqReplyInfoDto.getMiniProAppId());
            hm.put("miniProGhId", faqReplyInfoDto.getMiniProGhId());
            faqReply.setContent(Tools.getStrEmpty(JSONObject.toJSONString(hm)));
        } else if (faqReply.getType() == 3) { //添加微信好友名片回复
            hm.put("wxid", faqReplyInfoDto.getWxid());
            hm.put("workWxid", faqReplyInfoDto.getWorkWxid());
            faqReply.setContent(Tools.getStrEmpty(JSONObject.toJSONString(hm)));
        } else if (faqReply.getType().intValue() == 4) { //拉群规则
            hm.put("content", faqReplyInfoDto.getPullGroupRuleJsonStr());
            faqReply.setContent(Tools.getStrEmpty(JSONObject.toJSONString(hm)));
        } else if (faqReply.getType().intValue() == 5) { //超级问答
            hm.put("content", faqReplyInfoDto.getSuperReplyJsonStr());
            faqReply.setContent(Tools.getStrEmpty(JSONObject.toJSONString(hm)));
        } else if(faqReply.getType().intValue() == 6){ //关键词拉群（风险监控）
            hm.put("content", faqReplyInfoDto.getPullGroupByKeywordJsonStr());
            faqReply.setContent(Tools.getStrEmpty(JSONObject.toJSONString(hm)));
        }

        Integer now = DateUtil.getNowTime();
        faqReply.setUpdateTime(now);
        faqReplyMapper.updateById(faqReply);

        // 删除关键字
        faqKeywordMapper.delByReplyId(faqReplyInfoDto.getId(), faqReplyInfoDto.getMerId());

        //关键词list
        for (FaqKeywordInfoDto faqKeywordInfoDto : faqReplyInfoDto.getFaqKeywordInfoDtoList()) {

            faqKeywordInfoDto.setMerId(faqReplyInfoDto.getMerId());

            if (faqKeywordInfoDto.getType() == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "触发类型不能为空");
            }
            if (StringUtils.isBlank(faqKeywordInfoDto.getKeyword())) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CIKUKEY_NULL);
            }
            if (StringUtils.isBlank(faqKeywordInfoDto.getDeviceType())) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备类型不能为空");
            }

            //最大时间为30天内
            if (Tools.getInteger(faqKeywordInfoDto.getMaxTime()).intValue() > 30 * 24 * 60) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "同一用户最大时间不能超过30天(30*24*60)");
            }

            //未选择机器人，判断该关键字是否存在，
            if (Tools.getLong(faqKeywordInfoDto.getDeviceUniqueId()).longValue() == 0) {
                FaqKeywordQuery faqKeywordQuery = new FaqKeywordQuery();
                faqKeywordQuery.setMerId(faqKeywordInfoDto.getMerId());
                faqKeywordQuery.setKeyword(faqKeywordInfoDto.getKeyword());
                faqKeywordQuery.setDeviceType(faqKeywordInfoDto.getDeviceType());
                List<FaqKeyword> faqKeywordList = faqKeywordMapper.findByList(faqKeywordQuery);
                if (faqKeywordList != null && faqKeywordList.size() > 0) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, String.format(ResponseMsg.CIKUKEY_EXIST, faqKeywordInfoDto.getKeyword()));
                }
            } else {//选择了机器人，
                //1-判断该机器人下是否关键字重复
                FaqKeyword nowKey = faqKeywordMapper.getByKeywordAndDeviceUniqueId(faqKeywordInfoDto.getKeyword(), faqReplyInfoDto.getMerId(), faqKeywordInfoDto.getDeviceUniqueId(), faqKeywordInfoDto.getDeviceType());
                if (nowKey != null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, String.format(ResponseMsg.CIKUKEY_EXIST, faqKeywordInfoDto.getKeyword()));
                }
                //2-判断是否有未选择机器人配置了该关键字
                FaqKeyword nowKey_0 = faqKeywordMapper.getByKeywordAndDeviceUniqueId(faqKeywordInfoDto.getKeyword(), faqReplyInfoDto.getMerId(), 0L, faqKeywordInfoDto.getDeviceType());
                if (nowKey_0 != null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, String.format(ResponseMsg.CIKUKEY_EXIST, faqKeywordInfoDto.getKeyword()));
                }
            }


            FaqKeyword ck_new = new FaqKeyword();
            BeanUtils.copyProperties(faqKeywordInfoDto, ck_new);
            ck_new.setId(IdWorker.getId());
            ck_new.setReplyId(faqReplyInfoDto.getId());
            ck_new.setMerId(faqReplyInfoDto.getMerId());
            ck_new.setPlatform(0);//0客户端(个微/企微);1公众号;2小程序;3app;(预留字段)
            ck_new.setCreateTime(now);
            ck_new.setUpdateTime(now);
            //会员标签
            ck_new.setUserTags(Tools.getStrEmpty(JSONObject.toJSONString(faqKeywordInfoDto.getUserTagsList())));
            //忽略自定义标签
            ck_new.setIgnoreTags(Tools.getStrEmpty(JSONObject.toJSONString(faqKeywordInfoDto.getIgnoreTagsList())));
            //忽略会员备注列表
            ck_new.setIgnoreRemarks(Tools.getStrEmpty(JSONObject.toJSONString(faqKeywordInfoDto.getIgnoreRemarksList())));
            //风控规则
            ck_new.setRiskRule(Tools.getStrEmpty(JSONObject.toJSONString(faqKeywordInfoDto.getRiskRule())));

            faqKeywordMapper.insertSelective(ck_new);
        }
    }

    /**
     * 删除
     *
     * @param faqReplyIdListDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Transactional
    public void deleteFaqReply(FaqReplyIdListDto faqReplyIdListDto) {

        List<Long> idList = faqReplyIdListDto.getIdList();

        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        for (Long id : idList) {
            // 删除关键字
            faqKeywordMapper.delByReplyId(id, faqReplyIdListDto.getMerId());
            faqReplyMapper.deleteById(id, faqReplyIdListDto.getMerId());
        }
    }

    /**
     * 查询智能回复回复语详情
     *
     * @param faqReplyIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public FaqReplyInfoVo findFaqReplyInfo(FaqReplyIdDto faqReplyIdDto) {
        if (faqReplyIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        FaqReply faqReply = faqReplyMapper.selectById(faqReplyIdDto.getId(), faqReplyIdDto.getMerId());

        if (faqReply == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该回复语不存在");
        }

        FaqReplyInfoVo faqReplyInfoVo = new FaqReplyInfoVo();
        BeanUtils.copyProperties(faqReply, faqReplyInfoVo);

        //分组信息
        if (faqReply.getGroupId() != null) {
            FaqReplyGroup faqReplyGroup = faqReplyGroupMapper.selectById(faqReply.getGroupId(), faqReply.getMerId());
            if (faqReplyGroup != null) {
                faqReplyInfoVo.setGroupName(faqReplyGroup.getName());
            }
        }

        JSONObject contentJSONObject = null;
        try {
            contentJSONObject = JSONObject.parseObject(faqReply.getContent());
        }catch (Exception e){

        }

        if (contentJSONObject == null) {
            contentJSONObject = new JSONObject();
        }

        if (faqReply.getType() == 0) {//常规回复
            faqReplyInfoVo.setContent(contentJSONObject.getString("content"));
        } else if (faqReply.getType() == 1) {//卡片回复
            faqReplyInfoVo.setCardTitle(contentJSONObject.getString("cardTitle"));
            faqReplyInfoVo.setCardUrl(contentJSONObject.getString("cardUrl"));
            faqReplyInfoVo.setCardImg(contentJSONObject.getString("cardImg"));
            faqReplyInfoVo.setCardDesc(contentJSONObject.getString("cardDesc"));
            //--2023-11-27修改
            faqReplyInfoVo.setAppName(contentJSONObject.getString("appName"));
            faqReplyInfoVo.setAppId(contentJSONObject.getString("appId"));
            faqReplyInfoVo.setAppVersion(contentJSONObject.getString("appVersion"));
        } else if (faqReply.getType() == 2) {//小程序回复
            faqReplyInfoVo.setMiniProName(contentJSONObject.getString("miniProName"));
            faqReplyInfoVo.setMiniProTitle(contentJSONObject.getString("miniProTitle"));
            faqReplyInfoVo.setMiniProUrl(contentJSONObject.getString("miniProUrl"));
            faqReplyInfoVo.setMiniProDesc(contentJSONObject.getString("miniProDesc"));
            faqReplyInfoVo.setMiniImgPwdStr(contentJSONObject.getString("miniImgPwdStr"));
            faqReplyInfoVo.setMiniImgStr(contentJSONObject.getString("miniImgStr"));
            faqReplyInfoVo.setMiniImgPwdStrWxwork(contentJSONObject.getString("miniImgPwdStrWxwork"));
            faqReplyInfoVo.setMiniImgStrWxwork(contentJSONObject.getString("miniImgStrWxwork"));
            faqReplyInfoVo.setMiniImgUrl(contentJSONObject.getString("miniImgUrl"));
            faqReplyInfoVo.setMiniProAppId(contentJSONObject.getString("miniProAppId"));
            faqReplyInfoVo.setMiniProGhId(contentJSONObject.getString("miniProGhId"));
        } else if (faqReply.getType() == 3) {//微信好友名片
            faqReplyInfoVo.setWxid(contentJSONObject.getString("wxid"));
            faqReplyInfoVo.setWorkWxid(contentJSONObject.getString("workWxid"));
        } else if (faqReply.getType() == 4) { //拉群规则
            faqReplyInfoVo.setContent(contentJSONObject.getString("content"));
            faqReplyInfoVo.setPullGroupRuleJsonStr(contentJSONObject.getString("content"));
        } else if (faqReply.getType() == 5) { //超级问答
            faqReplyInfoVo.setContent(contentJSONObject.getString("content"));
            faqReplyInfoVo.setSuperReplyJsonStr(contentJSONObject.getString("content"));
        }else if (faqReply.getType() == 6) { //关键词拉群（风险监控）
            faqReplyInfoVo.setContent(contentJSONObject.getString("content"));
            faqReplyInfoVo.setPullGroupByKeywordJsonStr(contentJSONObject.getString("content"));
        }

        //关键字对象列表
        FaqKeywordQuery faqKeywordQuery = new FaqKeywordQuery();
        faqKeywordQuery.setMerId(faqReply.getMerId());
        faqKeywordQuery.setReplyId(faqReply.getId());
        List<FaqKeyword> faqKeywordList = faqKeywordMapper.findByList(faqKeywordQuery);
        if (faqKeywordList != null && faqKeywordList.size() > 0) {
            List<FaqKeywordInfoVo> faqKeywordInfoVoList = new ArrayList<>();
            List<String> keywordList = new ArrayList<>();
            for (FaqKeyword faqKeyword : faqKeywordList) {
                FaqKeywordInfoVo faqKeywordInfoVo = new FaqKeywordInfoVo();
                BeanUtils.copyProperties(faqKeyword, faqKeywordInfoVo);

                //会员标签
                String userTags = faqKeyword.getUserTags();
                if (StringUtils.isNotBlank(userTags)) {
                    try {
                        List<Long> userTagsList = JSONObject.parseArray(userTags, Long.class);
                        faqKeywordInfoVo.setUserTagsList(userTagsList);
                    } catch (Exception e) {

                    }
                }

                //忽略自定义标签
                String ignoreTags = faqKeyword.getIgnoreTags();
                if (StringUtils.isNotBlank(ignoreTags)) {
                    try {
                        List<String> ignoreTagsList = JSONObject.parseArray(ignoreTags, String.class);
                        faqKeywordInfoVo.setIgnoreTagsList(ignoreTagsList);
                    } catch (Exception e) {

                    }
                }

                //忽略会员备注标签
                String ignoreRemarks = faqKeyword.getIgnoreRemarks();
                if (StringUtils.isNotBlank(ignoreRemarks)) {
                    try {
                        List<String> ignoreRemarksList = JSONObject.parseArray(ignoreRemarks, String.class);
                        faqKeywordInfoVo.setIgnoreRemarksList(ignoreRemarksList);
                    } catch (Exception e) {

                    }
                }

                //风控规则
                String riskRuleStr = faqKeyword.getRiskRule();
                if (StringUtils.isNotBlank(riskRuleStr)) {
                    try {
                        RiskRule riskRule = JSONObject.parseObject(riskRuleStr, RiskRule.class);
                        faqKeywordInfoVo.setRiskRule(riskRule);
                    } catch (Exception e) {

                    }
                }

                faqKeywordInfoVoList.add(faqKeywordInfoVo);
                keywordList.add(faqKeyword.getKeyword());
            }
            faqReplyInfoVo.setFaqKeywordInfoVoList(faqKeywordInfoVoList);
            faqReplyInfoVo.setKeywordList(keywordList);
        }
        return faqReplyInfoVo;
    }

    /**
     * 设置是否开启
     *
     * @param faqReplayStatusDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Transactional
    public void updateStatus(FaqReplayStatusDto faqReplayStatusDto) {

        List<Long> idList = faqReplayStatusDto.getIdList();
        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        for (Long id : idList) {
            FaqReply faqReply = faqReplyMapper.selectById(id, faqReplayStatusDto.getMerId());

            if (faqReply == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "回复语id不存在或已删除");
            }

            faqReply.setStatus(Tools.getInteger(faqReplayStatusDto.getStatus()));

            //修改回复语状态
            int i = faqReplyMapper.updateStatusById(faqReply);
            if (i != 1) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "网络异常,请稍后重试!");
            }
        }
    }

}
